package net.wangds.utils;

import net.wangds.log.helper.LogHelper;

import java.nio.ByteBuffer;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2020/9/21 14:59.
 */
public abstract class AbstractBcdUtils {

    /**
     * 压缩缓存.
     *
     * @param bufIn 未压缩的缓存.
     * @return 结果.
     */
    public static ByteBuffer compact2ReadModInit(ByteBuffer bufIn) {

        int iInLen = bufIn.limit();

        boolean bInLenIsOdd = iInLen % 2 == 1;
        int iOutLen = (iInLen / 2) + (bInLenIsOdd ? 1 : 0);//计算输出长度

        ByteBuffer out = ByteBuffer.allocate(iOutLen);

        int iPos = 0;
        int hi, lo; //高位和低位数据
        while (out.hasRemaining()) {
            hi = iPos==0&&bInLenIsOdd?0:bufIn.get(); //长度为奇数的第一位高位用0补位
            lo = bufIn.get();
            byte btVal = (byte)(((hi&0xF)<<4)|(lo&0xF));
            out.put(btVal);
            iPos++;
        }


        //调整到读取状态
        out.rewind();


        return out;
    }

    /**
     * 解压数据.
     *
     * @param bufIn 数据.
     * @return 解压之后的缓存数据.
     * <p>新构建的缓存对象</p>
     */
    public static ByteBuffer uncompact2ReadModInit(ByteBuffer bufIn) {
        int iLenOfIn = bufIn.remaining();
        LogHelper.dev("数据长度:"+iLenOfIn);
        bufIn.mark();

        /// BEGIN 压缩数据首位处理
        byte firstNumPair = bufIn.get();
        byte hi = (byte)((firstNumPair&0xF0)>>4);
        byte lo = (byte)(firstNumPair&0xF);

        int iLenOfOut = iLenOfIn*2;//输出缓存大小
        if(hi==0){ //首位为0时，长度-1
            iLenOfOut-=1;
        }
        //写入首位数据
        ByteBuffer bbOut = ByteBuffer.allocate(iLenOfOut);
        if(hi>0){
            bbOut.put(hi);
        }
        bbOut.put(lo);
        /// END 压缩数据首位处理


        while(bufIn.hasRemaining()){
            byte curNumPair = bufIn.get();
            hi = (byte)((curNumPair&0xF0)>>4);
            lo = (byte)(curNumPair&0xF);
            bbOut.put(hi);
            bbOut.put(lo);
        }

        bufIn.reset();

        return bbOut;

    }
}
